package com.base.user.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.ldap.DefaultLdapUsernameToDnMapper;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.userdetails.LdapUserDetailsManager;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author 谭心武
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/public").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        .loginPage("/login")
                        .permitAll()
                )
                .logout(LogoutConfigurer::permitAll
                );
        return http.build();
    }
    @Bean
    public UserDetailsContextMapper userDetailsContextMapper() {
        // 创建自定义映射器实例:ml-citation{ref="5,6" data="citationList"}
        return new CustomUserDetailsContextMapper();
    }
    @Bean
    public DefaultSpringSecurityContextSource contextSource() {
        // 替换为你的 LDAP 服务器配置
        return new DefaultSpringSecurityContextSource("ldap://localhost:389/dc=example,dc=com");
    }

    @Bean
    public LdapUserDetailsManager ldapUserDetailsManager(
            DefaultSpringSecurityContextSource contextSource, UserDetailsContextMapper userDetailsContextMapper
    ) {
        LdapUserDetailsManager manager = new LdapUserDetailsManager(contextSource);
        manager.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=people", "uid"));
        manager.setUserDetailsMapper(userDetailsContextMapper);
        return manager;
    }

}
